package com.genesis.yunnanji.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.Toolbar;

import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.genesis.yunnanji.MainActivity;
import com.genesis.yunnanji.R;
import com.genesis.yunnanji.bean.LoginBean;

import com.genesis.yunnanji.config.GenesisApiConfig;
import com.genesis.yunnanji.fragment.FastLogin;
import com.genesis.yunnanji.fragment.PasswordLogin;

import com.genesis.yunnanji.view.DataLoadingDialog;
import com.google.gson.Gson;
import com.umeng.qq.tencent.IUiListener;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.Map;

import es.dmoral.toasty.Toasty;


public class Login extends BaseActivity {

    @ViewInject(R.id.iv_login_QQ)
    private ImageView QQlogin;
    @ViewInject(R.id.iv_login_WX)
    private ImageView WXlogin;
    @ViewInject(R.id.rb_login_loginway)
    private CheckBox loginMode;
    @ViewInject(R.id.tb_login_toolbar)
    private Toolbar mToolbar;
    @ViewInject(R.id.tv_login_fastre)
    private TextView tvRegister;
    @ViewInject(R.id.tv_login_forget)
    private TextView tvFindPassword;
    private Fragment[] mFragments;
    private int mIndex;
    private Intent intent;
    private int loginselect;
    private DataLoadingDialog dialog;
//    private TencentUtil tencentUtil;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, R.layout.activity_login);
//        tencentUtil = new TencentUtil(this);
//        tencentUtil.setOnLoginCallback(new TencentUtil.OnLoginCallback() {
//            @Override
//            public void onPublishResult(int status, String message, Object result) {
//                switch (status) {
//                    case 0:
//                        Toast.makeText(Login.this, message, Toast.LENGTH_SHORT).show();
//                        break;
//                    case -1:
//                        Toast.makeText(Login.this, message, Toast.LENGTH_SHORT).show();
//                        break;
//                    default:
//                        System.out.println("=====>登陆结果：" + new Gson().toJson(result));
//                        break;
//                }
//            }
//        });
    }


    @Override
    protected void initView(Bundle savedInstanceState) {
        dialog = new DataLoadingDialog(context);
        dialog.setCanceledOnTouchOutside(false);
        mToolbar.setTitle("");
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        FastLogin fastLogin = FastLogin.newInstance("快捷登陆");
        PasswordLogin passwordLogin = PasswordLogin.newInstance("密码登陆");
        mFragments = new Fragment[]{fastLogin, passwordLogin};
        FragmentTransaction ft =
                getSupportFragmentManager().beginTransaction();
        ft.add(R.id.fl_login_frame, passwordLogin).commit();
        setIndexSelected(0);
    }

    @Override
    protected void setUpView() {

    }


    @Event(value = {R.id.iv_login_QQ, R.id.iv_login_WX, R.id.tv_login_fastre, R.id.tv_login_forget}, type = View.OnClickListener.class)
    private void QQWXlogin0(View v) {
        switch (v.getId()) {
            case R.id.iv_login_QQ:
                dialog.show();
                loginselect = 0;
//                tencentUtil.login(this);
                AuthLogin(SHARE_MEDIA.QQ);
                break;
            case R.id.iv_login_WX:
                dialog.show();
                loginselect = 1;
                AuthLogin(SHARE_MEDIA.WEIXIN);
                break;
            case R.id.tv_login_fastre:
                intent = new Intent(context, Register.class);
                startActivity(intent);
                break;
            case R.id.tv_login_forget:
                intent = new Intent(context, FindPassword.class);
                startActivity(intent);
                break;
        }
    }

    public void AuthLogin(SHARE_MEDIA platform) {
        if (Build.VERSION.SDK_INT >= 23) {
            String[] mPermissionList = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CALL_PHONE,
                    Manifest.permission.READ_LOGS, Manifest.permission.READ_PHONE_STATE,
                    Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.SET_DEBUG_APP,
                    Manifest.permission.SYSTEM_ALERT_WINDOW, Manifest.permission.GET_ACCOUNTS, Manifest.permission.WRITE_APN_SETTINGS};
            ActivityCompat.requestPermissions(this, mPermissionList, 123);
        }
        UMAuthListener umAuthListener = new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {
                Log.e("lk", "start");
            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                Log.e("lk", "complete");
                QQLogin(map.get("uid"), map.get("name"), map.get("gender"), map.get("iconurl"), "");
            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                Log.e("lk", "error");
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {
                Log.e("lk", "cancel");
            }
        };
        UMShareAPI mShareAPI = UMShareAPI.get(Login.this);
        mShareAPI.getPlatformInfo(Login.this, platform, umAuthListener);
    }

    private void setIndexSelected(int index) {
        if (mIndex == index) {
            return;
        }
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction ft = fragmentManager.beginTransaction();


        ft.hide(mFragments[mIndex]);
        if (!mFragments[index].isAdded()) {
            ft.add(R.id.fl_login_frame, mFragments[index]).show(mFragments[index]);
        } else {
            ft.show(mFragments[index]);
        }

        ft.commit();
        mIndex = index;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /*if (loginselect == 0)
            tencentUtil.onActivityResult(requestCode, resultCode, data);
        else
            */UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

    }


    private void QQLogin(String open_id, String nickname, String sex, String photo, String birthday) {
        Log.e("lk", "login");
        String url = "";
        if (loginselect == 0) {
            url = GenesisApiConfig.HOST + GenesisApiConfig.QQ_LOGIN;
        } else if (loginselect == 1) {
            url = GenesisApiConfig.HOST + GenesisApiConfig.WEIXIN_LOGIN;
        }
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("openid", open_id);
        params.addBodyParameter("nickname", nickname);
        if (sex.equals("男")) {
            params.addBodyParameter("sex", 1 + "");
        } else if (sex.equals("女")) {
            params.addBodyParameter("sex", 2 + "");
        } else {
            params.addBodyParameter("sex", 0 + "");
        }
        params.addBodyParameter("photo", photo);
        params.addBodyParameter("birthday", birthday);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                dialog.dismiss();
                Gson gson = new Gson();
                LoginBean loginBean = gson.fromJson(result, LoginBean.class);
                if (loginBean.getStatus() == 200) {
                    genesisUtils.setAppToken(loginBean.getResult().get__apptoken__());
                    if (loginselect == 0) {
                        genesisUtils.setCustomConnect("qq");
                    } else if (loginselect == 1) {
                        genesisUtils.setCustomConnect("weixin");
                    }
                    Intent intent = new Intent();
                    intent.setAction(PasswordLogin.LOGIN_STATUS);
                    intent.putExtra("msg", "login");
                    Login.this.sendBroadcast(intent);
                    Login.this.finish();
                    Toasty.success(context, loginBean.getMessage(), Toast.LENGTH_SHORT).show();
                    EventBus.getDefault().post(new String("login"));
                } else {
                    Toasty.error(context, loginBean.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                dialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                dialog.dismiss();
            }

            @Override
            public void onFinished() {
                dialog.dismiss();
            }
        });

    }

}
